package com.hontech.bread.store

import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.os.Environment
import com.hontech.bread.R
import com.hontech.bread.app.AppContext
import com.hontech.bread.utils.log
import com.hontech.bread.utils.runCPU
import com.hontech.bread.utils.runIO
import com.hontech.bread.utils.stringById
import java.io.File

val rootDir = Environment.getExternalStorageDirectory()
val advDir = File(rootDir, "adv")

object Store {

    private val dbPath = File(rootDir, "bread_data.db").path

    private val ctx = SqliteCtx(dbPath)
    val db: SQLiteDatabase = ctx.writableDatabase

    suspend fun init() {
        if (ctx.updateFlag) {
            drop()
        }
        runIO { advDir.mkdirs() }
        createTable()
        StoreCargo.init()
    }

    private suspend fun createTable() = runCPU {
        db.execSQL(StoreProduct.CREATE_SQL)
        db.execSQL(StoreCargo.CREATE_SQL)
        db.execSQL(Order.CREATE_SQL)
        db.execSQL(StoreLog.CREATE_SQL)
    }

    private suspend fun drop() = runCPU {
        db.execSQL(StoreProduct.DROP_SQL)
        db.execSQL(StoreCargo.DROP_SQL)
        db.execSQL(Order.DROP_SQL)
    }
}


private class SqliteCtx(name: String) : SQLiteOpenHelper(AppContext, name, null, 6) {

    var updateFlag = false
        private set

    override fun onCreate(db: SQLiteDatabase?) {

    }

    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
        log("${stringById(R.string.t1733460848_290)}${databaseName}")
        updateFlag = true
    }
}





